/* 和小程序通讯的websocket */
import Vue from 'vue'
import Vuex from 'vuex'
import Storage from 'vue-ls'
Vue.use(Vuex)
let rec = null,
	timer = null,
	csId = '';
import {
	sendWx
} from '@/api/index'

const minProjectStore = {
	state: {
		websock: null,
		conncted: false,
		minProjectLogin: 0, //小程序是否登录
		showAnswerProgress: {
			num: 0
		},
		showSendTempTestPaper: {
			num: 0
		}, //发送临时题
		minStopTemp: 0, //小程序临时题结束
		minStopTest: 0, //小程序随堂检测结束
		minStopHomework: 0, //小程序课后作业结束
		showsendHomework: {
			num: 0
		},
		showhomeworkUpdateStart: {
			num: 0
		},
		minfinishCourse: 0, //小程序下课
		//临时题结束
		showTempTrueAnswerRank: {
			num: 0,
		},
		minWebsockdk: 0,
		mingetAnswerProgress: {
			num: 0
		}, //继续推送答题进度
		mingetsendTime: {
			num: 0
		}, //同步试题时长和倒计时
		showResources: 0,
		previewResources: {
			index: -1,
			deg: 0
		},
		getResources: 0,
		speechAnswerList: [], //语音识别内容
		speechAnswerAIList: [], //AI识别答案
		rkvoiceCharList: [], //老师语音提问问题和学生答案
		cosyvoiceCharList: [], //语音测评返回
		klgpointList: [], //知识点返回
		hasAudio: false, //是否有了测评mp3
	},
	mutations: {
		MINPROJECT_INIT(state, url) {
			let that = this;
			console.log(JSON.stringify(url))

			if (state.conncted) {
				return
			}
			console.log('开始连接', new Date().getTime())
			state.websock = new WebSocket(url);
			let csIds = url.split('/');
			csId = csIds[csIds.length - 1];
			state.websock.onopen = () => {
				console.log("小程序连接成功！", state.deviceType, new Date().getTime());
				state.conncted = true;
				//发送心跳信息
				rec && clearTimeout(rec);
				timer && clearTimeout(timer);
				this.commit('MINPROJECT_SEND', csId);
				timer = setInterval(() => {
					this.commit('MINPROJECT_SEND', csId);
				}, 1 * 1000);


			}

			state.websock.onmessage = (callBack) => {
				console.log('method', callBack)
				let data = callBack.data;
				let msg = null;
				try {
					data = JSON.parse(callBack.data)
					try {
						msg = JSON.parse(data.data)
					} catch (e) {
						msg = data.data
					}
				} catch (e) {
					//TODO handle the exception
				}
				let method = data.fun;

				//console.log(method)
				console.log(method + JSON.stringify(msg))
				switch (method) {
					case 'minProjectLogin': {
						//state.minProjectLogin = state.minProjectLogin + 1;
						state.minProjectLogin = new Date().getTime();
						break;
					}
					case 'sendTopic': {
						let {
							isSbtive,
							testType,
							testTime,
							testQuestId,
							topicType,
							istempTestTime
						} = msg;
						let testData = Vue.ls.get('testData');
						//console.log("testData"+JSON.stringify(testData))
						let newtestTime = testTime ? parseFloat(testTime) : testTime;
						let newtestType = parseFloat(testType);
						Vue.ls.set('testData', Object.assign({}, testData, {
							state: -1,
							sendState: -1,
							isSbtive,
							testType: newtestType,
							testTime: newtestTime,
							//testQuestId,//这里不存试题id是因为，如果小城连续发两道不同试题，需要结束前一道，如果改变缓存，不能进行比较了
							istempTestTime: istempTestTime ? 1 : 0
						}));

						let beginClassData = Vue.ls.get('beginClass');
						Vue.ls.set('beginClass', Object.assign({}, {
							...beginClassData
						}, {
							topicType: 99,
						}));
						state.showAnswerProgress = {
							num: state.showAnswerProgress.num + 1,
							state: -1,
							sendState: -1,
							isSbtive,
							testType: newtestType,
							testTime: newtestTime,
							testQuestId,
							topicType: 99,
							istempTestTime: istempTestTime ? 1 : 0
						}

						break;
					}
					case 'sendTempTestPaper': {
						let {
							testTime,
							testQuestId,
							topicType,
							bigNum,
							subNum,
							topicId,
							anScopeEnd,
							anScopeStart,
							sdTestQuestId,
							sendTime,
							totalanswer,
						} = msg;
						let newtestTime = testTime ? parseFloat(testTime) : testTime;
						state.showSendTempTestPaper = {
							num: state.showSendTempTestPaper.num + 1,
							bigNum: bigNum,
							subNum: subNum,
							anScopeEnd,
							anScopeStart,
							topicType: topicType - 0,
							topicId: topicId,
							sdTestQuestId,
							sendTime,
							totalanswer,
							testTime: newtestTime,
							testQuestId
						}
						break;
					}
					//结束临时题时选择答案跳转统计排名
					case 'tempTrueAnswer': {
						let {
							answer,
							topicId
						} = msg;
						state.showTempTrueAnswerRank = {
							num: state.showTempTrueAnswerRank.num + 1,
							totalanswer: answer,
							topicId
						}
						break;
					}
					//结束临时题
					case 'stopTemp': {
						state.minStopTemp = state.minStopTemp + 1;
						break;
					}
					//结束随堂检测
					case 'stopTest': {
						state.minStopTest = state.minStopTest + 1;
						break;
					}
					//结束课后作业
					case 'stopHomework': {
						state.minStopHomework = state.minStopHomework + 1;
						break;
					}
					//发送课后作业
					case 'sendHomework': {
						//{"testQuestId":"1780903820348358656","classId":"1772802746961887232","csId":"1808073689682411520","isSbtive":0,"testTime":"","testType":1}
						let {
							testQuestId,
							topicType,
							testType,
							isSbtive,
							csId,
							testTime
						} = msg;

						let newtestTime = testTime ? parseFloat(testTime) : testTime;
						let newtestType = parseFloat(testType);
						let testData = Vue.ls.get('testData');
						//console.log("testData"+JSON.stringify(testData))
						Vue.ls.set('testData', Object.assign({}, testData, {
							state: -1,
							sendState: -1,
							isSbtive,
							testType: newtestType,
							testQuestId,
							//topicType:99,
							testTime: newtestTime
						}));

						let beginClassData = Vue.ls.get('beginClass');
						Vue.ls.set('beginClass', Object.assign({}, {
							...beginClassData
						}, {
							topicType: 99,
						}));
						//let tempTestData = Vue.ls.get('tempTestData');

						// console.log("咔咔咔咔咔咔啊"+JSON.stringify(tempTestData))
						// Vue.ls.set('tempTestData', Object.assign({}, {...tempTestData}, {
						// 	topicType:99,
						// 	testType
						// }));


						state.showsendHomework = {
							num: state.showsendHomework.num + 1,
							testQuestId,
							topicType: 99,
							testType: newtestType,
							isSbtive,
							csId,
							testTime: newtestTime
						}
						break;
					}
					//收取课后作业
					case 'homeworkUpdateStart': {
						let {
							testQuestId,
							topicType,
							testType,
							isSbtive,
							csId
						} = msg;
						let newtestType = parseFloat(testType);
						let testData = Vue.ls.get('testData');
						//console.log("testData"+JSON.stringify(testData))
						Vue.ls.set('testData', Object.assign({}, testData, {
							state: -1,
							sendState: -1,
							isSbtive,
							testType: newtestType,
							testQuestId,
							topicType: 99,
							testTime: null,
							istempTestTime: 0
						}));

						let beginClassData = Vue.ls.get('beginClass');
						Vue.ls.set('beginClass', Object.assign({}, {
							...beginClassData
						}, {
							topicType: 99,
						}));

						// let tempTestData = Vue.ls.get('tempTestData');
						// Vue.ls.set('tempTestData', Object.assign({}, {...tempTestData}, {
						// 	topicType:99,
						// 	testType
						// }));
						state.showhomeworkUpdateStart = {
							num: state.showhomeworkUpdateStart.num + 1,
							testQuestId,
							topicType: 99,
							testType,
							isSbtive,
							csId
						};
						break;
					}
					case 'getAnswerProgress': {
						let {
							testQuestId
						} = msg;
						state.mingetAnswerProgress = {
							num: state.mingetAnswerProgress.num + 1,
							testQuestId
						};
						break;
					}
					//获取倒计时和试题时长
					case 'getsendTime': {
						let {
							testQuestId,
							topicType,
							testType,
							isSbtive,
							testTime,
						} = msg;
						state.mingetsendTime = {
							num: state.mingetsendTime.num + 1,
							testQuestId,
							topicType: 99,
							testType,
							isSbtive,
							state: 0,
							sendState: 0,
							testTime
						};
						break;
					}
					//下课
					case 'finishCourse': {
						state.minfinishCourse = state.minfinishCourse + 1;
						break;
					}
					//小程序意外断开
					case 'wxdk': {
						state.minWebsockdk = state.minWebsockdk + 1;
						break;
					}

					//显示上课资源
					case 'showResources': {
						state.showResources = state.showResources + 1;
						break;
					}
					//显示上课资源
					case 'hideResources': {
						state.showResources = 0;
						break;
					}
					//预览图片
					case 'PreviewResources': {
						state.previewResources = {
							...msg
						};
						break;
					}
					// 刷新资源
					case 'getResources': {
						state.getResources = state.getResources + 1;
						break;
					}
					//AI识别答案
					case 'voice': {
						state.speechAnswerAIList.push(data)
						break;
					} //推送语音识别消息
					case 'voiceChar': {
						state.speechAnswerList.push(data)
						break
					} //老师问题
					case 'rkvoiceChar': {
						state.rkvoiceCharList.push(data)
						break
					}
					case 'cosy': {
						state.hasAudio = true;
						break
					}
					//语音测评返回
					case 'cosyvoiceChar': {
						state.cosyvoiceCharList.push(data)
						break
					}
					//老师问题识别成功返回
					case 'rkVoiceEnd': {
						state.rkvoiceCharList.push(data)
						break
					} //知识点返回
					case 'klgpoint': {
						state.klgpointList.push(data)
						break
					}

				}
			}
			state.websock.onerror = function(e) { //错误
				console.log("小程序websocket ws错误！");
				state.conncted = false;
				/* 判断是否需要重连 */
				let beginClassData = Vue.ls.get('beginClass');
				if (beginClassData && beginClassData.csId) {
					that.commit('MINPROJECT_RECONNECT', url);
				}

			}
			state.websock.onclose = function(e) { //关闭
				console.log("小程序websocket ws关闭！", new Date().getTime());
				console.log(e);
				state.conncted = false;
				/* 判断是否需要重连 */
				let beginClassData = Vue.ls.get('beginClass');
				if (beginClassData && beginClassData.csId) {
					that.commit('MINPROJECT_RECONNECT', url);
				}
			}

		},
		MINPROJECT_SEND(state, message) {
			// console.log("ws发送信息！", message, state.conncted);
			state.conncted && state.websock.send(message);
			//state.websock.send(JSON.stringify(message) + "\n");
		},
		MINPROJECT_CLOSE(state) {
			state.websock.close(); //离开路由之后断开websocket连接
			//清空重连逻辑
			console.log('开始主动关闭小程序websocket')
			state.machId = "";
			rec && clearTimeout(rec);
			timer && clearTimeout(timer);
		},
		MINPROJECT_RECONNECT(state, url) {
			if (state.conncted) return;
			rec && clearTimeout(rec);
			timer && clearTimeout(timer);
			// 延迟5秒重连  避免过多次过频繁请求重连
			rec = setTimeout(() => {
				console.log('开始重新链接')
				this.commit('MINPROJECT_INIT', url);
			}, 3000);
		},
		CLEARAUDIOURL(state) {
			state.hasAudio = false
		}
	},
	actions: {
		MINPROJECT_INIT({
			commit
		}, url) {
			try {
				commit('MINPROJECT_INIT', url)

			} catch (e) {
				commit('MINPROJECT_RECONNECT', url)
			}

		},
		MINPROJECT_SEND({
			commit
		}, p) {
			commit('MINPROJECT_SEND', p)
		},
		MINPROJECT_CLOSE({
			commit
		}) {
			commit('MINPROJECT_CLOSE')
		},
		sendWx({
			commit
		}, sendMsg) {
			return new Promise((resolve) => {
				console.log('sendMsg', sendMsg)
				sendWx(sendMsg).then(da => {
					resolve()
				}).finally(() => {

				});
			})
		},
	}
}
export default minProjectStore